<template>
  <div class="login-body">
    <div class="login-container">
      <div class="head">
        <img class="logo" src="../assets/logo.png" />
        <div class="name">
          <div class="title">高中信息技术</div>
          <div class="tips">题库系统</div>
        </div>
      </div>
      <el-form label-position="top" :rules="state.rules" :model="state.ruleForm" ref="loginForm" class="login-form">
        <el-form-item label="账号" prop="username">
          <el-input type="text" v-model.trim="state.ruleForm.username" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model.trim="state.ruleForm.password" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captch_code"> 
          <div class="flexColumnDisplay" >       
          <el-input type="text" v-model.trim="state.ruleForm.captcha_code" autocomplete="off" @blur="checkCapchaCodeBlur"></el-input>
          <el-text v-show="state.captchaCodeOk" size="small"> <el-icon><SuccessFilled /></el-icon> </el-text>
          <img :src="state.captcha_picture" class="captch_picture" @click="updateCaptchaClick" />
        </div>
        </el-form-item>
        <img class="captchpicture" src=""/>
        <el-form-item>
          <div style="color: #333">登录表示您已同意<a>《服务条款》</a></div>      
          <el-checkbox v-model="state.checked" @change="!state.checked">下次自动登录</el-checkbox>
        </el-form-item>
        <div class="twoButton">
          <el-button type="primary" @click="submitForm()" :disabled="state.submitButtonOK">登录</el-button>
          <el-button  type="warning" @click="signInClick()">注册</el-button>         
          <el-button  type="danger" @click="resetPasswordClick()">忘记密码</el-button>
     
        </div>
      </el-form>
      <!-- <div class="otherLogin">
        <span>其他登录</span>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="待开发"
          placement="top"
        >
          <el-icon size="30" ><Iphone /></el-icon> 
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="light"
          content="待开发"
          placement="top"
        >
        <img style="width: 35px; height: 35px"  src="../assets/weixin.png"  />
        </el-tooltip>
        <img style="width: 35px; height: 35px"  src="../assets/qq.png"  />
        <img style="width: 35px; height: 35px"  src="../assets/dingding.png"  />
        <img style="width: 35px; height: 35px"  src="../assets/zhifubao.png"  />
      </div> -->
    </div>
  </div>
</template>

<script setup>
import axios from '@/utils/axios'
import { reactive, ref } from 'vue'
import { localSet, imageUrlPrefix } from '@/utils'
import { onMounted } from "@vue/runtime-core"
import router from '../router'
import { SuccessFilled, Iphone } from '@element-plus/icons-vue'
import { ElMessage, ElNotification  } from 'element-plus'

const loginForm = ref(null)
let state = reactive({
  otherLoginUrls: [
    imageUrlPrefix+'weixin.png',
    imageUrlPrefix+'qq.png',
    imageUrlPrefix+'zhifubao.png', 
    imageUrlPrefix+'dingding.png',
  ],
  captchaCodeOk: false,
  submitButtonOK: true,
  captcha_picture: '',
  ruleForm: {
    username: '',
    password: '',
    captcha_code: '',
  },
  checked: true,
  rules: {
    username: [
      { required: 'true', message: '账户不能为空', trigger: 'blur' }
    ],
    password: [
      { required: 'true', message: '密码不能为空', trigger: 'blur' }
    ],
    captcha_code: [
      { required: 'true', message: '验证码不能为空', trigger: 'blur' }
    ],
  }
})

// 通过服务器检验校对验证码是否正确
const sendCheckCapchaCode=()=>{
    let params = {clientCode: state.clientCode, captchaCode: state.ruleForm.captcha_code}
    console.log("开始检测验证码：")
    axios.get('/CheckCaptchaCode/', {params}).then(res => {
      console.log(res)
        if(res.code==200){         
          state.captchaCodeOk = true          
        }else{
          state.captchaCodeOk = false      
        }
        state.submitButtonOK = !state.captchaCodeOk
    })
    .catch((error)=>{
      console.log("检测验证码失败", error)
    })
  }
  // 处理输入验证码事件
  const checkCapchaCodeBlur=()=>{
    sendCheckCapchaCode()
  }


//获取图像
const getCaptchaPictureWithClientCode=()=>{
    const min = 10000000
    const max = 99999999
    const a = Math.floor(Math.random() * (max - min + 1)) + min
    state.clientCode = a
    console.log("发送clientCode", state.clientCode)
    let params = { clientCode: state.clientCode }
    axios.get('/CaptchaPictureWithClientCode/', {params}).then(res => {
        console.log('收到图片:',res)
        if(res.code==200){
            state.captcha_picture='data:image/png;base64,' + res.data.results
            console.log("获取成功图片成功", res)
        }else{
            ElMessage.error("获取图像失败，请联系管理员！")
        }          
    })
    .catch((error)=>{
      console.log("获取图像失败", error)
    })
  }
  //第一次加载页面，直接获取图片
  onMounted(()=>{
    // console.log("其他登录", state.otherLoginUrls)
    getCaptchaPictureWithClientCode()
  })
  //提交登录表单
  const submitForm = async () => {
    loginForm.value.validate((valid) => {
      if (valid) {
        axios.post('/login/', {
          username: state.ruleForm.username || '',
          // passwordMd5: md5(state.ruleForm.password),
          password: state.ruleForm.password,
          rand_code: state.ruleForm.captcha_code
        }).then(res => {
          console.log('登录成功：', res)
          if (res.code==200){
            console.log('用户信息：',res)
            localSet('token', res.data.results.token)
            localSet('user_information', res.data.results.user)
            localSet('isLogin', true)
            ElMessage.success("登录成功了！")          
            window.location.href = '/'
          }else{
            ElNotification({
              title: '登录错误',
              message: res.message,
              type: 'error',
            })
            console.log("没有成功",res)
            getCaptchaPictureWithClientCode()
            state.ruleForm.captcha_code=''
          }
          })
          .catch((error)=>{
            console.log(error)
            getCaptchaPictureWithClientCode()
            state.ruleForm.captcha_code=''
          })
      } else {
        console.log('error submit!!')
        return false;
      }
    })
  }
// 点击图片更新
const updateCaptchaClick=(val)=>{
  state.ruleForm.captcha_code = ""
  getCaptchaPictureWithClientCode()
}
//跳转到注册页面
const signInClick=()=>{
  console.log("我要去注册拉~")
  // window.location.href = '/signin'
  router.push({path:'/signin', replace: true})
}
// 重置密码按钮点击事件
const resetPasswordClick=()=>{
  router.push("/resetPassword")
}
</script>

<style scoped>
  .login-body {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    background-color: #fff;
  }
  .login-container {
    width: 420px;
    height: 500px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0px 21px 41px 0px rgba(0, 0, 0, 0.2);
  }
  .head {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0 10px 0;
  }
  .head img {
    width: 80px;
    height: 80px;
    margin-right: 10px;
  }
  .head .title {
    font-size: 28px;
    color: #1BAEAE;
    font-weight: bold;
  }
  .head .tips {
    font-size: 12px;
    color: #999;
  }
  .login-form {
    width: 70%;
    margin: 0 auto;
  }
  .login-form >>> .el-form--label-top .el-form-item__label {
    padding: 0;
  }
  .login-form >>> .el-form-item {
    margin-bottom: 0;
  }
  .captch_picture{
    width:80px;
    height: 30px;
    cursor:pointer;
  }
  .twoButton{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .flexColumnDisplay{
    display: flex;
    flex-flow: row nowrap;
  }
  .otherLogin{
    padding: 10px;
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
  }
</style>